<template>
  <div class="login-container">
    <el-card class="login-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="登录" name="login">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item label="登录方式">
              <el-radio-group v-model="loginForm.way">
                <el-radio label="密码">密码登录</el-radio>
                <el-radio label="验证码">验证码登录</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="identifier">
              <el-input v-model="loginForm.identifier" :placeholder="loginForm.way === '密码' ? '请输入工号/手机号' : '请输入手机号'" prefix-icon="User" />
            </el-form-item>
            <el-form-item prop="password" v-if="loginForm.way === '密码'">
              <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password />
            </el-form-item>
            <el-form-item prop="code" v-if="loginForm.way === '验证码'">
              <el-input v-model="loginForm.code" placeholder="请输入验证码" prefix-icon="Lock">
                <template #append>
                  <el-button @click="getVerificationCode(loginForm.identifier)" :disabled="isGettingCode">{{ getCodeButtonText }}</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width: 100%" @click="handleLogin">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="注册" name="register">
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
            <el-form-item prop="personName">
              <el-input v-model="registerForm.personName" placeholder="请输入用户名" prefix-icon="User" />
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号" prefix-icon="Phone" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password />
            </el-form-item>
            <el-form-item prop="code">
              <el-input v-model="registerForm.code" placeholder="请输入验证码" prefix-icon="Lock">
                <template #append>
                  <el-button @click="getVerificationCode(registerForm.phone)" :disabled="isGettingCode">{{ getCodeButtonText }}</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="title">
              <el-select v-model="registerForm.title" placeholder="请选择职称" style="width: 100%">
                <el-option label="普通操作人员" value="普通操作人员" />
                <el-option label="部门经理" value="部门经理" />
                <el-option label="系统管理员" value="系统管理员" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width: 100%" @click="handleRegister">注册</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const activeTab = ref('login')

// 登录表单
const loginForm = reactive({
  identifier: '',
  password: '',
  code: '',
  way: '密码' // 新增登录方式参数
})

const loginRules = computed(() => {
  const rules: any = {
    identifier: [
      { required: true, message: loginForm.way === '密码' ? '请输入工号/手机号' : '请输入手机号', trigger: 'blur' },
      { 
        validator: (rule: any, value: any, callback: any) => {
          if (loginForm.way === '验证码' && !/^1[3-9]\d{9}$/.test(value)) {
            callback(new Error('请输入正确的手机号码'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
  };
  if (loginForm.way === '密码') {
    rules.password = [{ required: true, message: '请输入密码', trigger: 'blur' }];
  } else {
    rules.code = [{ required: true, message: '请输入验证码', trigger: 'blur' }];
  }
  return rules;
});

// 注册表单
const registerForm = reactive({
  personName: '',
  phone: '',
  password: '',
  title: '',
  code: ''
})

const registerRules = {
  personName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  title: [{ required: true, message: '请选择职称', trigger: 'change' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const loginFormRef = ref()
const registerFormRef = ref()

const isGettingCode = ref(false);
const getCodeButtonText = ref('获取验证码');
let timer: number | null = null;

// 获取验证码
const getVerificationCode = async (phone: string) => {
  if (!phone) {
    ElMessage.warning('请输入手机号');
    return;
  }
  // 只有在验证码登录方式下才发送验证码
  if (activeTab.value === 'login' && loginForm.way !== '验证码') {
    return;
  }
  if (isGettingCode.value) return;

  isGettingCode.value = true;
  let countdown = 60;
  getCodeButtonText.value = `重新获取(${countdown}s)`;

  timer = setInterval(() => {
    countdown--;
    if (countdown > 0) {
      getCodeButtonText.value = `重新获取(${countdown}s)`;
    } else {
      clearInterval(timer!);
      isGettingCode.value = false;
      getCodeButtonText.value = '获取验证码';
      timer = null;
    }
  }, 1000);

  try {
    const res = await axios.get(
      import.meta.env.VITE_API_URL + `account/getCode?phone=${phone}`
    );
    if (res.data) {
      ElMessage.success('验证码已发送');
    } else {
      ElMessage.error('验证码发送失败');
      clearInterval(timer!);
      isGettingCode.value = false;
      getCodeButtonText.value = '获取验证码';
      timer = null;
    }
  } catch (error) {
    ElMessage.error('验证码发送失败');
    clearInterval(timer!);
    isGettingCode.value = false;
    getCodeButtonText.value = '获取验证码';
    timer = null;
  }
};

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await axios.post(
          import.meta.env.VITE_API_URL + 'account/login',
          {
            identifier: loginForm.identifier,
            password: loginForm.way === '密码' ? loginForm.password : undefined, // 验证码登录时不发送密码
            code: loginForm.way === '验证码' ? loginForm.code : undefined, // 密码登录时不发送验证码
            way: loginForm.way
          }
        )
        if (res.data.success) {
          ElMessage.success('登录成功')
          // 使用Pinia存储用户信息
          userStore.setUserInfo({
            id: res.data.data.personId,
            name: res.data.data.personName,
            deptId: res.data.data.deptId,
            deptName: res.data.data.deptName,
            title: res.data.data.title
          })
          // 跳转到首页
          router.push('/main')
        } else {
          ElMessage.error(res.data.message || '登录失败')
        }
      } catch (error) {
        ElMessage.error('登录失败')
      }
    }
  })
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return
  await registerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await axios.post(
          import.meta.env.VITE_API_URL + 'account/register',
          {
            personName: registerForm.personName,
            phone: registerForm.phone,
            password: registerForm.password,
            title: registerForm.title,
            code: registerForm.code
          }
        )
        if (res.data.success) {
          ElMessage.success('注册成功')
          activeTab.value = 'login' // 切换到登录标签
          // 清空注册表单
          registerFormRef.value.resetFields()
        } else {
          ElMessage.error(res.data.message || '注册失败')
        }
      } catch (error) {
        ElMessage.error('注册失败')
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
}

:deep(.el-tabs__nav) {
  width: 100%;
  display: flex;
}

:deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
}
</style>